if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}
Array.prototype.max = function() {
  return Math.max.apply(null, this);
};

Array.prototype.min = function() {
  return Math.min.apply(null, this);
};

var start=/@/ig;
var word=/@(\w+)/ig;

var notJson={
    "err": 400,
    "msg": []
};

var isDebugChecking=true;
var totalbdayupdated=0;
var totalnewnotifictionsupdated=0;
var nLastNotifiedActivityId=0;
var nLeastNotfiedActID=0,nMaxNotifiedActID=0;

var requserid=0;
var requserprivacysetting=0;
//common popus
var commonpopus={'newShare':1,'addLocation':2,'clusterWrapper':3,'createcluster':4,'friendRequestPopup':5};
//common bpo popups
var bpopopupcommonids={'idchangefeedprivacy':1};
//post action types
var postactiontype={'like_post':1,'share_post':8,'update_privacy_setting_for_post':3,'comment_post':4,'like_comment':5,'remove_comment':6};
//follow types
var followType={profile:1,page:2,technopath:3,blog:4};
var baseUrl="";
var notification_type_mine=["friend_added","followed","friend_req_found"];
//configuration default settings
var isModifyPvtSettings=false; /* set to true only if you want privacy setting to be change always with post*/

//(.format() method: alternative of string.format of c# eg: "{0} count".format(6))
// First, checks if it isn't implemented yet. 
if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

entityMap = {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '\"',
    "'": '\'',
    '/': '\/'
};

function escapeString(string) {
    return string;
    /*
    return String(string).replace(/[&<>"'\/]/g, function(s) {
        return entityMap[s];
    });*/
}

function getNumberFromString(strNum)
{
    var matches = strNum.match(/\d+/);
    return parseInt(matches[1]);
}

function escapeString1(string) {
    //return string.replace("DBL|QUOTE","\'");
    return String(string).replace(/[&<>"'\/]/g, function(s) {
        return entityMap[s];
    });
    
}

function setPrivacySetting(pSeq){
    //document.getElementById("prvset").style.visibility='visible';
    if(!isNaN(pSeq)){
        isModifyPvtSettings=true;
        var sharedWithval= $("#prvset").val();
        //alert(sharedWithval);
        //alert(sharewithtags.cluster);
       if(parseInt(sharedWithval)==parseInt(jsprivacytypes.choose_cluster)){
            var methodstr="uPSetCluster(\'frmstupdt\',this.value);";
            $("#st_myclusters").html(getClusterWithChangeEvnt("st_selcluster","Select Cluster",methodstr));
            $("#st_myclusters").show();
        }
        else{
            uPSet("frmstupdt");    
        }
        
      //  document.getElementById("prvset").style.visibility='hidden';
    }
}


function showHideMenuToggle($idName){
    //alert("hu");
    $("#privacy-menu").toggle();        
    //$("#privacy-menu").hide();
}

function ust(frmName){
    var formS = document.getElementById(frmName);
    var titleval =(document.getElementById("Post[post_title]"))?(document.getElementById("Post[post_title]").value):"";
    var descriptionstr =(document.getElementById("Post[post_content]"))?(document.getElementById("Post[post_content]").value):"";
    var term =(document.getElementById("ajx_status_update"))?(document.getElementById("ajx_status_update").value):"";
    var postcategoryid=(document.getElementById("Post[Parent_ID]"))?(document.getElementById("Post[Parent_ID]").value):"";
    var sharedpostid=(document.getElementById("post_shared_id"))?(document.getElementById("post_shared_id").value):"";
    var sharedpostmsg=(document.getElementById("post_share_msg"))?(document.getElementById("post_share_msg").value):"";
    var postsharedwithtypeid=(document.getElementById("share_with_options"))?(document.getElementById("share_with_options").value):"";
    var postsharedwithclusterid=(document.getElementById("share_with_cluster"))?(document.getElementById("share_with_cluster").value):"";
    var locstr=(document.getElementById("locstr"))?(document.getElementById("locstr").value):"";
    var taggedUsers=(document.getElementById("sttaggedusers"))?(document.getElementById("sttaggedusers").value):"";
    var url = $("#"+frmName).attr( "action" );
    //var imgpostdata=$("#"+frmName).find("#uploadedimagedata").val();
    
    var postMedias =(document.getElementById("status_file_hidden"))?(document.getElementById("status_file_hidden").value):"";

    if(isNaN(postcategoryid) || postcategoryid=="" || typeof postcategoryid == undefined){
        postcategoryid=0;
    }
    var nposttype=0;
    if(document.getElementById('nPostType')){
        nposttype=document.getElementById('nPostType').value;
    }
    var npvtsetting=0;
    if(document.getElementById('prvset')){
        npvtsetting=document.getElementById('prvset').value;
    }
    var Clustered_ID=0;
    if(document.getElementById('st_selcluster')){
        Clustered_ID=document.getElementById('st_selcluster').value;
    }
    
    if(locstr=="none" || locstr=="NONE"){
        locstr="";
    }
    
    var emotionstext=$("form#frmstupdt #st_emotionsfeeling_div").html();    
    // Send the data using post
    var posting = $.post( url, { 
                                    sStatus: term, 
                                    'title':titleval,
                                    'description':descriptionstr, 
                                    nPrivSet: npvtsetting, 
                                    'nPostType':nposttype,
                                    isModifyPrivSetting:false,
                                    'Post[Parent_ID]':postcategoryid,
                                    'post_shared_id':sharedpostid,
                                    'post_share_msg':sharedpostmsg,
                                    'share_with_options':postsharedwithtypeid,
                                    'share_with_cluster':postsharedwithclusterid,
                                    'post_location':locstr,
                                    'taggedinUsers':taggedUsers,
                                    'postMedias':postMedias,
                                    'emotionstext':emotionstext,
                                    'share_with_cluster':Clustered_ID
                                } );
  // Put the results in a div
    posting.done(function( data ) { 
        data=escapeString(data);
        if(data!=""){
            var jsonParsed=$.parseJSON(data);
            //console.log(jsonParsed);
            /*if(document.getElementById("errconsole")){
                document.getElementById("errconsole").innerHTML=data;
            }*/
            if(!isNaN(jsonParsed.err)){ //means have some code
                switch(parseInt(jsonParsed.err)){
                    case 200:
                            //alert(jsonParsed.msg);
                            getTopFiles(requserid,requserprivacysetting,nposttype, postcategoryid);
                            break;
                    default:
                            alert(jsonParsed.msg);
                            break;
                }
            }
        }
        else{
            console.log("Something went wrong in ajax script");
        }
        
    });
}

function uPSet(frmName){
    var formS = document.getElementById(frmName);
    var url = $("#"+frmName).attr( "action" );
    // Send the data using post
    var posting = $.post( url, { nPrivSet: document.getElementById('prvset').value, isModifyPrivSetting:isModifyPvtSettings } );
  // Put the results in a div
    posting.done(function( data ) {
        //alert(data);
        data=escapeString(data);
        var jsonParsed=$.parseJSON(data);
        //console.log(jsonParsed);
        /*if(document.getElementById("errconsole")){
            document.getElementById("errconsole").innerHTML=data;
        }*/
        if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        alert(jsonParsed.msg);
                        break;
                default:
                        alert(jsonParsed.msg);
                        break;
            }
        }
    });
}

function uPSetCluster(frmName,clusterdrpid){
    var formS = document.getElementById(frmName);
    var url = $("#"+frmName).attr( "action" );
    var clusterid=clusterdrpid;
    // Send the data using post
    var posting = $.post( url, { pSetClusterId:clusterid, nPrivSet: document.getElementById('prvset').value, isModifyPrivSetting:isModifyPvtSettings } );
  // Put the results in a div
    posting.done(function( data ) {
        //alert(data);
        data=escapeString(data);
        var jsonParsed=$.parseJSON(data);
        //console.log(jsonParsed);
        /*if(document.getElementById("errconsole")){
            document.getElementById("errconsole").innerHTML=data;
        }*/
        if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        alert(jsonParsed.msg);
                        break;
                default:
                        alert(jsonParsed.msg);
                        break;
            }
        }
    });
}


function uFeedPSet(frmName,jsonPost){
    var formS = document.getElementById(frmName);
    var url = $("#"+frmName).attr( "action" );
    // Send the data using post
    var posting = $.post( url, jsonPost );
  // Put the results in a div
    posting.done(function( data ) {
        data=escapeString(data);
        var jsonParsed=$.parseJSON(data);
        //console.log(jsonParsed);
        /*if(document.getElementById("errconsole")){
            document.getElementById("errconsole").innerHTML=data;
        }*/
        if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        alert(jsonParsed.msg);
                        break;
                default:
                        alert(jsonParsed.msg);
                        break;
            }
        }
    });
}

function fCreateCluster(frmName){
    var formS = document.getElementById(frmName);
    var url = $("#"+frmName).attr( "action" );
    // Send the data using post
    var posting = $.post( url, { actiontype: 'add_cluster', cluster_name:$("#"+frmName).find("#txtclustername").val() } );
  // Put the results in a div
    posting.done(function( data ) {
        //alert(data);
        data=escapeString(data);
        var jsonParsed=$.parseJSON(data);
        //console.log(jsonParsed);
        /*if(document.getElementById("errconsole")){
            document.getElementById("errconsole").innerHTML=data;
        }*/
        if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        alert(jsonParsed.msg);
                        updateMyClusters();
                        break;
                default:
                        alert(jsonParsed.msg);
                        break;
            }
        }
        disablePopup();
    });
}
function getNewsFeeds(feedfor,lastfeed,feedsetting){
	
//	 alert(baseUrl);
	/*if(baseUrl==""){
		baseUrl="http://www.go4softwares.in/";
	}*/
    getUserFiles(false,true,feedfor,feedsetting,lastfeed);
    
	var requestedPage="ajax/read_newsfeeds.php";
	 var urlstr=baseUrl+requestedPage;	 
	 //alert(urlstr+"\n\n "+reqFilterIDs+"\n\n pricerange: "+priceRange);	 
	 $.ajax({
	  	type: "POST",
	  	url: urlstr,
	  	cache: false,
	  	data: { uid: feedfor, feedsetting: feedsetting,feedid:lastfeed}
	})
	.done(function( msg ) {	
	   msg=escapeString(msg);
		$("#tweets").append(msg);
	  	//alert( "Data Saved: " + msg );
	})
	.fail(function(msg) { 
		console.log(msg);
//		alert("error"); 
	})
    .always(function() { 
		//alert("complete"); 
        $("#overlay").fadeOut();
	});
}


function showFriendRequestPopup(){
    showCommonPopupBoxes(commonpopus.friendRequestPopup,0);
}

function showAddLocationBox(updatefor){
    showCommonPopupBoxes(commonpopus.addLocation,0);
}

function likeMe(postid,feedtypeid,feedparentid){
    performPostActions(postid,postactiontype.like_post,'','',feedtypeid,feedparentid,0,'','');
}
function likeComment(commentid,postid){
    performPostActions(postid,postactiontype.like_comment,'','','','',commentid,'','');
}

function showShareBox(postid,feedtypeid,feedparentid){
    plotPostSnapshot(postid,feedtypeid,feedparentid);
    if(document.getElementById("myclusters")){
        document.getElementById("myclusters").innerHTML=getCluster("share_with_cluster","Share with");
    }
    showCommonPopupBoxes(commonpopus.newShare,postid);
}

function getCluster(clusterid,clusterdefaulttext){
    var clusterHtml='<select id="{0}"  name="{0}" {2}><option value="" selected="selected">{1}</option></select>';
    if(document.getElementById("my_updated_cluster")){
        clusterHtml=document.getElementById("my_updated_cluster").innerHTML;
    }
    clusterHtml=clusterHtml.format(clusterid,clusterdefaulttext,"");
    return clusterHtml;
}
function getClusterWithChangeEvnt(clusterid,clusterdefaulttext,methodstr){
    var method_apply='onchange="'+methodstr+'"';
    var clusterHtml='<select id="{0}"  name="{0}" {2}><option value="" selected="selected">{1}</option></select>';
    if(document.getElementById("my_updated_cluster")){
        clusterHtml=document.getElementById("my_updated_cluster").innerHTML;
    }
    clusterHtml=clusterHtml.format(clusterid,clusterdefaulttext,method_apply);
    return clusterHtml;
}

function showMyClusters(clusterid,clustername){
    
    showClusterFList(clusterid,clustername,true);
    
}

function updateMyClusters(){
    ajaxCallShowMyClusters();
    
}
function ajaxGetClusterFriends(clusterid){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/getAjaxHtml.php",
	  	cache: false,
        async:false,
	  	data: { actiontype:'show_clusters_friends_for_popup',clusterid:clusterid}
	})
	.done(function( msg ) {	
	  return msg;
        //on success
        
		  
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
    
}
function ajaxCallShowMyClusters(){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/getAjaxHtml.php",
	  	cache: false,
	  	data: { actiontype:'show_clusters_drp'}
	})
	.done(function( msg ) {	
	   //alert(msg);
        //on success
        var clusterDetail=[];
        if(msg.search("[SEP]")>0){
            clusterDetail=msg.split("[SEP]");
        }
        if(clusterDetail.length>0){
            if(clusterDetail[0]){
                if(clusterDetail[0].search("<select")>0){
                    if(document.getElementById("my_updated_cluster")){
                        document.getElementById("my_updated_cluster").innerHTML=clusterDetail[0];
                    }
                }
            }
            if(clusterDetail[1]){
                $("#clusters").find('li:not(.clusternotchange)').remove();
                $("#clusters").append(clusterDetail[1]);                
            }
        }
		  
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
    
}
function createCluster(){
    showCommonPopupBoxes(commonpopus.createcluster,0);    
}

function showPrivacyBox(postid,feedtypeid,feedparentid){
    if(document.getElementById("myclustersprivacy")){
        document.getElementById("myclustersprivacy").innerHTML= "<b>Choose Cluster: </b>"+getCluster("show_with_cluster","Show with");
    }
    showCommonbpoPopupBoxes(bpopopupcommonids.idchangefeedprivacy,postid);
}

function showCommonbpoPopupBoxes(popupid,postid){
    var popuptoshow="";
    var commonpopuscls=""; 
    switch(popupid){
        case bpopopupcommonids.idchangefeedprivacy:
            popuptoshow="idchangefeedprivacy";
        break;
        break;
    }
    for(commonbpopopup in bpopopupcommonids ){
        if(popuptoshow.toLowerCase() !=commonbpopopup.toLowerCase()){
            $("."+commonbpopopup).css("display","none");
        }
    }
    if(document.getElementById("post_id_for_privacy")){
        $("#"+popuptoshow).find("#post_id_for_privacy").val(postid);    
    }
    
    $("#"+popuptoshow).show();
}

function showCommonPopupBoxes(popupclass,uniqueid){
    loading(); // loading
	setTimeout(function(){ // then show popup, deley in .5 second
		loadPopupClass(popupclass,uniqueid); // function show popup 
	}, 500); // .5 second
	return false;
}
function plotPostSnapshot(postid,feedtypeid,feedparentid){
    performPostActions(postid,postactiontype.share_post,'','',feedtypeid,feedparentid,0,'','');
}
function updatePrivacySettings(postid){
    var feedtypeid=0,feedparentid=0;
    performPostActions(postid,postactiontype.update_privacy_setting_for_post,'','',feedtypeid,feedparentid,0,'','');
}

function clearDefaultText(strText,idStr){
    if(document.getElementById(idStr)){
          if(document.getElementById(idStr).innerHTML==strText){
            document.getElementById(idStr).innerHTML="";
          }
    }
}

function showDefaultText(strText,idStr){
    if(document.getElementById(idStr) && document.getElementById(idStr).innerHTML.replace(strText,'').length<=0){
        document.getElementById(idStr).innerHTML=strText;
    }
}

function SetCaretAtEnd(elem) {
    var elemLen = elem.value.length;
    // For IE Only
    if (document.selection) {
        // Set focus
        elem.focus();
        // Use IE Ranges
        var oSel = document.selection.createRange();
        // Reset position to 0 & then set at end
        oSel.moveStart('character', -elemLen);
        oSel.moveStart('character', elemLen);
        oSel.moveEnd('character', 0);
        oSel.select();
    }
    else if (elem.selectionStart || elem.selectionStart == '0') {
        // Firefox/Chrome
        elem.selectionStart = elemLen;
        elem.selectionEnd = elemLen;
        elem.focus();
    } // if
} // SetCaretAtEnd()
    
function commentMe(postid,commentid,e){
    var feedtypeid=0,feedparentid=0;
    var code = event.keyCode ? event.keyCode : event.which;
    //alert("keycode: "+code);                    
    if(code==10){
        var contenthtml=$("#"+commentid).html();
        $("#"+commentid).html(contenthtml+"<br>");
        SetCaretAtEnd(document.getElementById(commentid));
    }
    else if (code == 13) {
        var commentMsg=$("#"+commentid).html();
        var taggedEmailsAnchors=$("#"+commentid).find(".aftaguid");
        var taggedCounts=taggedEmailsAnchors.length;
        var taggedemails=[];
        for(var vtag=0;vtag<taggedCounts;vtag++){            
            taggedemails.push(getUrlParameterByName(taggedEmailsAnchors[vtag].href,"t"));
        }
        var imgsrcs=getCommentsImagesSrc(postid);
        performPostActions(postid,postactiontype.comment_post,'',commentMsg,feedtypeid,feedparentid,0,taggedemails,imgsrcs);
        
        $("#"+commentid).html("");
        $("#multiformCmntUpload"+postid).find('#cmntupload_filelist').find("li").remove();
        
        return false;
    }
        var content=$("#"+commentid).text();
        var go= content.match(start);
        var name= content.match(word);
        var dataString = 'tagSearch='+ name;
        if(go!=null && name!=null && go.length>0 && name.length>0)
        {
            var commentsContainer=commentid.replace("_txtcomment","_comments");
            var commentthreadid=commentid.replace("_txtcomment","");
            //$("#msgbox").slideDown('show');
            //$("#display").slideUp('show');
            //$("#msgbox").html("Type the name of someone or something...");
            if(name.length>0)
            {
                $.ajax({
                    type: "POST",
                    url: "ajax/tagsearch.php",
                    data: 'tagSearch='+ name+'&threadid='+commentthreadid,
                    cache: false,
                    success: function(htmldata)
                    {
                        $("#"+commentsContainer).find(".tagmsgbox").hide();
                        $("#"+commentthreadid+"_flist").html(htmldata).show();
                    }
                });
            }
            //return false;
        }
    
    
    
    
}
function commentOn(postid){
    var commentMsgid=postid+"_txtcomment";
    var commentMsg="";
    var feedtypeid=0,feedparentid=0;
    if(document.getElementById(commentMsgid)){
        commentMsg=document.getElementById(commentMsgid).value;
        if(commentMsg.length>0){
            performPostActions(postid,postactiontype.comment_post,'',commentMsg,feedtypeid,feedparentid,0,'','');
        }
        else{
            alert("Please enter a comment");
        }
    }
    
}

function getUrlParameterByName(urltoparse,name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(urltoparse);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

function performPostActions(postid,actiontype,feedsetting,feedcomment,feedtypeid,feedparentid,cmntid,taggedEmailsArr,imgsrcsArr){
    //alert("postid: "+postid+" actiontype: "+ actiontype);
    
    var requestedPage="ajax/generictask.php";
	 var urlstr=requestedPage;
     
     	 
	 //alert(urlstr+"\n\n "+reqFilterIDs+"\n\n pricerange: "+priceRange);	 
	 $.ajax({
	  	type: "POST",
	  	url: urlstr,
	  	cache: false,
	  	data: { feedid: postid,commentid:cmntid,actiontype:actiontype, feedsetting: feedsetting,feedcomment:feedcomment,feedtypeid:feedtypeid,feedparentid:feedparentid,'taggedusers':taggedEmailsArr,'uploadimgsrcs':imgsrcsArr}
	})
	.done(function( msg ) {	
	   //alert(msg);
       msg=escapeString(msg);
		switch(actiontype){
            case postactiontype.like_post:
                var likeid=postid+"_lcount";
                if(!isNaN(msg)){
                    if(document.getElementById(likeid)){
                        document.getElementById(likeid).innerHTML=parseInt(msg);
                    }
                }
                break;
            case postactiontype.like_comment:
                var likeid="cmt_"+cmntid;
                if(!isNaN(msg)){
                    if(document.getElementById(likeid)){
                        document.getElementById(likeid).innerHTML=parseInt(msg);
                    }
                }
                break;        
            case postactiontype.share_post: //it will just plot a image of shared post
                if(document.getElementById("posttoshare_snapshot")){
                    $("#posttoshare_snapshot").html(msg);
                }
                break;
            
            case postactiontype.update_privacy_setting_for_post:
                alert("privacy changed");
                break;
            case postactiontype.comment_post:
                if(msg.indexOf("<!--Comment-->")==0){
                    var commentid=postid+"_comments";
                    if(isNaN(msg)){
                        if(document.getElementById(commentid)){
                            document.getElementById(commentid).innerHTML=(msg);
                        }
                    }
                }
                $("#"+postid+"_txtcomment").val(""); 
                break;
            case postactiontype.sharer_post_snapshot:
                alert("post detail "+msg);
                break;      
            case postactiontype.remove_comment:
                if(!isNaN(msg) && parseInt(msg)==200){
                    $("#cmnt_row_"+cmntid).remove();
                    //alert("Post comment removed "+cmntid+" - "+msg);
                }
                
                break;
         }
	})
	.fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}

	 /************** start: functions. **************/
	function loading() {
		$("div.loader").show();  
	}
	function closeloading() {
		$("div.loader").fadeOut('normal');  
	}
	
	var popupStatus = 0; // set value
	
    function getSharePostSnapshot(postid){
        //posttoshare_snapshot
        if(document.getElementById("posttoshare_snapshot")){
            document.getElementById("posttoshare_snapshot").innerHTML="Snapshot is loading...";
        }
    }
	function loadPopupClass(popupclass,postid) { 
	   var clusterid=0;
		if(popupStatus == 0) { // if value is 0, show popup
        //var commonpopus={'newShare':1,'addLocation':2};
            var popuptoshow="";
            var commonpopuscls=""; 
            switch(popupclass){
                case commonpopus.newShare:
                    popuptoshow="newShare";
                    break;
                case commonpopus.addLocation:
                    popuptoshow="addLocation";
                    break;
                case commonpopus.clusterWrapper:
                    clusterid=postid;
                    popuptoshow="clusterWrapper";
                    break;
                case commonpopus.createcluster:
                    popuptoshow="createcluster";
                    break;
                case commonpopus.friendRequestPopup:
                    popuptoshow="friendRequestPopup";
                    break;
            }
            for(commonpopuscls in commonpopus ){
                if(popuptoshow.toLowerCase() !=commonpopuscls.toLowerCase()){
                    $("."+commonpopuscls).css("display","none");
                }
            }
            if(popupclass!=commonpopus.createcluster){
                if(document.getElementById("post_shared_id")){
                    $("."+popuptoshow).find("#post_shared_id").val(postid);    
                }
            }
            if(popupclass==commonpopus.clusterWrapper){
                if($("form#frmAddcluster").find("#hClusterid")){
                    $("form#frmAddcluster").find("#hClusterid").val(clusterid);    
                }
            }
            
            $("."+popuptoshow).show();
			closeloading(); // fadeout loading
			$("#toPopup").fadeIn(0500); // fadein popup div
			$("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
			$("#backgroundPopup").fadeIn(0001); 
			popupStatus = 1; // and set value to 1
		}	
	}
		
	function disablePopup() {
		if(popupStatus == 1) { // if value is 1, close popup
			$("#toPopup").fadeOut("normal");  
			$("#backgroundPopup").fadeOut("normal");  
			popupStatus = 0;  // and set value to 0
		}
	}

/** Notifications Work: By sujeet on 9 May 2014 **/


var userid=0;
var genericNotificationType={'feeds':1,'all':2,'mine':3,'only_birthday':4};


getNotifications(genericNotificationType.feeds,userid);
getNotifications(genericNotificationType.mine,userid);

var minutesT=1000*60*2;
var testing=10000;

if(!isDebugChecking){
    var myNotificationInterval=setInterval(function(){myTimer(userid)},testing);
    
    function myTimer() {
        getNotifications(genericNotificationType.feeds,userid);
        getNotifications(genericNotificationType.mine,userid);
        //window.clearInterval(myNotificationInterval);
    }
}

var friendRequestJson={};
var totalFriendRequest=0;

var friendAddedJson={};
var totalFriendAdded=0;

var followedJson={};
var totalFollowed=0;


var appsRequestJson={};
var totalAppsRequest=0;

var blogsRequestJson={};
var totalBlogsRequest=0;

var eventsRequestJson={};
var totalEventsRequest=0;

var inboxRequestJson={};
var totalInboxRequest=0;

var technoRequestJson={};
var totalTechnoRequest=0;

var bdayAlertsJson={};
var totalBdayAlerts=0;


function getRandomChoice()
{
    var min=1;
    var max=notification_type_mine.length;
    var randomNumber=Math.floor(Math.random()*(max-min+1)+min)-1;
    return randomNumber;
}


function getNotifications(notificationtype,userid){
    //alert("getNotifications ");
     var requestedPage="ajax/readNotifications.php";
	 var urlstr=baseUrl+requestedPage;
     var actiontype="get_feedsnotification"; //actiontype="get_allnotifications";	 
     
     var reqfor_notificationType=notification_type_mine[getRandomChoice()];
     switch(notificationtype){
        case genericNotificationType.feeds:
            actiontype="get_feedsnotification";
            break;
        case genericNotificationType.all:
            //actiontype="get_allnotifications";
            actiontype="get_feedsnotification";                        
            break;
        case genericNotificationType.mine:
            actiontype="get_minenotifications";
            break;
        case genericNotificationType.only_birthday:
            actiontype="get_minenotifications";
            reqfor_notificationType="birthday_alerts";
            break;
     }
	 //alert(urlstr+"\n\nactiontype: "+actiontype+"\n\n reqfor_notificationType: "+reqfor_notificationType);	 
	 $.ajax({
	  	type: "POST",
	  	url: urlstr,
	  	cache: false,
	  	data: { uid: userid, actiontype: actiontype,"notificationType":reqfor_notificationType}
	})
	.done(function( msg ) {
	   //alert(msg);
	   switch(notificationtype){
            case genericNotificationType.feeds:
                var feedJson=$.parseJSON(msg);
                //console.log(feedJson);
                //window.clearInterval(myNotificationInterval);
                break;
            case genericNotificationType.all:
                var feedJson=$.parseJSON(msg);
                
                //friend_request
                friendRequestJson=feedJson[0].friend_request;
                if(friendRequestJson.length>0){
					totalFriendRequest=friendRequestJson[0].total_friend_req;
	                friendRequestJson=friendRequestJson[0].Data;
	                //show updates
	                updateFriendNotification(totalFriendRequest,friendRequestJson);					
				}

                
                //
                appsRequestJson={};
                blogsRequestJson={};
                eventsRequestJson={};
                inboxRequestJson={};
                technoRequestJson={};
                
                //window.clearInterval(myNotificationInterval);
                break;
            case genericNotificationType.mine:
                var feedJson=$.parseJSON(msg);
                
                //friend_request
                friendRequestJson=feedJson[0].friend_request;
                if(friendRequestJson.length>0){
					totalFriendRequest=friendRequestJson[0].total_friend_req;
	                friendRequestJson=friendRequestJson[0].Data;
	                //show updates
	                updateFriendNotification(totalFriendRequest,friendRequestJson);					
				}

                //friends_added
                friendAddedJson=feedJson[0].friends_added;
                if(friendAddedJson.length>0){
					totalFriendAdded=friendAddedJson[0].total_friends_added;
	                friendAddedJson=friendAddedJson[0].Data;
	                //show updates
	                //updateFriendAddedByMyFriendsNotification(totalFriendAdded,friendAddedJson);
                    showFriendsAddedByMyFriends();					
				}

                //follows
                followedJson=feedJson[0].follows;
                if(followedJson.length>0){
					totalFollowed=followedJson[0].total_follwed_req;
	                followedJson=followedJson[0].Data;
	                //show updates
	                //updateFollowersNotification(totalFollowed,followedJson);
                    showFollowersFollowedByMyFriends();					
				}
                
                
                //
                appsRequestJson={};
                blogsRequestJson={};
                eventsRequestJson={};
                inboxRequestJson={};
                technoRequestJson={};
                
                //window.clearInterval(myNotificationInterval);
                break;
            case genericNotificationType.only_birthday:
                //alert(msg);
                var feedJson=$.parseJSON(msg);
                
                //friend_request
                bdayAlertsJson=feedJson[0].birthday_alerts;
                if(bdayAlertsJson.length>0){
					totalBdayAlerts=bdayAlertsJson[0].total_birthday;
	                bdayAlertsJson=bdayAlertsJson[0].Data;
	                //show updates
	                updateBirthdayNotification(totalBdayAlerts,bdayAlertsJson);					
				}
                break;
         }
	  	//alert( "Data Saved: " + msg );
	})
	.fail(function(msg) { 
		console.log(msg);
//		alert("error"); 
	})
    .always(function() { 
		//alert("complete"); 
        $("#overlay").fadeOut();
	});
}

function getFriendRequestsRow(uid,userplink,username,upicpath){
    var friendReqRow='<div class="friendrow" style="vertical-align: top;padding-bottom:5px;padding-top:5px;">';    
        friendReqRow+='<table style="width: 100%;">';
        friendReqRow+='<tbody><tr>';
        friendReqRow+='<td style="vertical-align: top;">';
        friendReqRow+='<a href="dna.php?t={0}"> <img class="userpiclass" src="{1}" height="50px" width="50px"></a>';
        friendReqRow+='</td>';
        friendReqRow+='<td style="vertical-align: top;">';
        friendReqRow+='<p><a href="dna.php?t={0}">{2}</a></p>';
        //friendReqRow+='<p>0 Common Friends</p>';
        friendReqRow+='<span class="btn">';
        //friendReqRow+='Friend Request Status : <span id="requeststatus_2">';
        //friendReqRow+='<b>Friends Request Sent.</b></span>';
        friendReqRow+='</span>';
        friendReqRow+='</td>';
        friendReqRow+='</tr>';
        friendReqRow+='</tbody></table>';
        friendReqRow+='</div>';
        friendReqRow=friendReqRow.format(userplink,upicpath,username);
        return friendReqRow;
}

function showFriendRequests(){
    var frequestHtml="";
    if(friendRequestJson.length>0){
        var fCount=0;
        var fReqJson={};
        for(fCount=0;fCount<friendRequestJson.length;fCount++){
            fReqJson=friendRequestJson[fCount];
            frequestHtml+=getFriendRequestsRow(fReqJson.uid,fReqJson.ulink,fReqJson.uname,fReqJson.upicpath);
        }
        if(document.getElementById("friendRequestPopupdiv")){
            document.getElementById("friendRequestPopupdiv").innerHTML=frequestHtml;
        }
        showFriendRequestPopup();
    }
}

function sleepMyTask(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

function notifyAlerts(frequestHtml1,notification_id,notificationType){
    if(notificationType=="follow"){
        //sleepMyTask(1000*20) 
        alertify.success(frequestHtml1+"Notification ID: follow"+notification_id);
           
    }
    else{
        alertify.success(frequestHtml1+"Notification ID: "+notification_id);
    }
    if(parseInt(notification_id)>0){  
        markAsReadNotification(notification_id);
    }
   //window.clearTimeout(timeoutID);
      
} 

function showFriendsAddedByMyFriends(){
    var frequestHtml="";
    var frequestHtml1="";
    if(friendAddedJson.length>0){
        var fCount=0;
        
        var fReqJson={};
        var fNewFrndJson={};
        var fNewTempJson={};
        var fnewCount=0;
        for(fCount=0;fCount<friendAddedJson.length;fCount++){
            fReqJson=friendAddedJson[fCount];
            frequestHtml=getFriendRequestsRow(fReqJson.uid,fReqJson.ulink,fReqJson.uname,fReqJson.upicpath);
            
            fNewFrndJson=friendAddedJson[fCount].info;
            for(fnewCount=0;fnewCount<fNewFrndJson.length;fnewCount++){
                fNewTempJson=fNewFrndJson[fnewCount].Data[0];
                frequestHtml1=frequestHtml+"<br> has added - "+getFriendRequestsRow(fNewTempJson.uid,fNewTempJson.ulink,fNewTempJson.uname,fNewTempJson.upicpath);
                //sleepMyTask(1000); 
                notifyAlerts(frequestHtml1,fReqJson.notification_id,"friend_added");
                //timeoutID = window.setTimeout(function () {notifyAlerts(frequestHtml1,fReqJson.notification_id,"friend_added")}, 3000*(fnewCount+1));
                //setInterval(function () {notifyAlerts(frequestHtml1)}, 400*(fnewCount+1));
                //notifyAlerts(frequestHtml1);  
            }
            
            
            
        }
        /*if(document.getElementById("friendRequestPopupdiv")){
            document.getElementById("friendRequestPopupdiv").innerHTML=frequestHtml;
        }
        showFriendRequestPopup();
        */
    }
}

function showFollowersFollowedByMyFriends(){
    var frequestHtml="";
    var frequestHtml1="";
    if(followedJson.length>0){
        var fCount=0;
        var fReqJson={};
        
        var fNewFrndJson={};
        var fNewTempJson={};
        var fnewCount=0;
        
        for(fCount=0;fCount<followedJson.length;fCount++){
            fReqJson=followedJson[fCount];
            frequestHtml=getFriendRequestsRow(fReqJson.uid,fReqJson.ulink,fReqJson.uname,fReqJson.upicpath);
            
            fNewFrndJson=followedJson[fCount].info;
            for(fnewCount=0;fnewCount<fNewFrndJson.length;fnewCount++){
                fNewTempJson=fNewFrndJson[fnewCount].Data[0];
                frequestHtml1=frequestHtml+"<br> has followed - "+getFriendRequestsRow(fNewTempJson.uid,fNewTempJson.ulink,fNewTempJson.uname,fNewTempJson.upicpath);
                //notifyAlerts(frequestHtml1);
                //sleepMyTask(3000); 
                notifyAlerts(frequestHtml1,fReqJson.notification_id,"follow")
                //timeoutID = window.setTimeout(function () {notifyAlerts(frequestHtml1,fReqJson.notification_id,"follow")},8000*1.5*parseInt(fnewCount+1));
            }
            //alertify.success(frequestHtml);
        }
        /*if(document.getElementById("friendRequestPopupdiv")){
            document.getElementById("friendRequestPopupdiv").innerHTML=frequestHtml;
        }
        showFriendRequestPopup();
        */
    }
}
function updateFriendNotification(totalFriendRequest,friendRequestJsonLocal){
    //console.log("total friend request: "+totalFriendRequest);
    //console.log("friend request data: ");
    //console.log(friendRequestJsonLocal);
    if(document.getElementById("tFCount")){
        document.getElementById("tFCount").innerHTML="({0})".format(totalFriendRequest);
    }
}

function showStatusTaggedBox(tagfor){
    var updateForid="";
    if(!isNaN(tagfor) && tagfor==1)
    {
        updateForid=1;
    }
    if(document.getElementById("status_tagging"+updateForid)){
        if(document.getElementById("status_tagging"+updateForid).style.display!="none"){
            document.getElementById("status_tagging"+updateForid).style.display="none";
            document.getElementById("sttaggedusers"+updateForid).value="";
        }
        else{
            document.getElementById("status_tagging"+updateForid).style.display="block";
        }
    }
    
}

function showTaggedPersons(flist){
    var friendList="";
    if(document.getElementById(flist)){
        friendList=document.getElementById(flist).value;
    }
    var friendsJson=$.parseJSON(friendList);
    showFriendsList(friendsJson);
}
function showFriendsList(friendRequestJson){
    var frequestHtml="";
    if(friendRequestJson.length>0){
        var fCount=0;
        var fReqJson={};
        for(fCount=0;fCount<friendRequestJson.length;fCount++){
            fReqJson=friendRequestJson[fCount];
            frequestHtml+=getFriendRequestsRow(fReqJson.uid,fReqJson.ulink,fReqJson.uname,fReqJson.upicpath);
        }
        if(document.getElementById("friendRequestPopupdiv")){
            document.getElementById("friendRequestPopupdiv").innerHTML=frequestHtml;
        }
        showFriendRequestPopup();
    }
}


function followMe(useridtofollow){
    if(!isNaN(useridtofollow)){
        followSources(useridtofollow,followType.profile);
    }
}

function followSources(idtofollow,followerType){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: { actiontype:'follow_sources',idtofollow:idtofollow,followtype:followerType}
	})
	.done(function( msg ) {
	   //alert(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        alert("followSources - "+jsonParsed.msg);
                        break;
                case 202:
                        alert("followSources - "+jsonParsed.msg);
                        break;
                default:
                        alert("followSources - "+jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}


function unFollowMe(useridtounfollow){
    if(!isNaN(useridtounfollow)){
        unfollowSources(useridtounfollow);
    }
}

function unfollowSources(idtounfollow){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: { actiontype:'unfollow_sources',idtounfollow:idtounfollow}
	})
	.done(function( msg ) {
	   //alert(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        alert(jsonParsed.msg);
                        break;
                case 202:
                        alert(jsonParsed.msg);
                        break;
                default:
                        alert(jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}


function markAsReadNotification(idtomark){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: { actiontype:'mark_as_read_mine_notificaion',idtomark:idtomark}
	})
	.done(function( msg ) {
	   //alert(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        console.log("markAsReadNotification - "+jsonParsed.msg);
                        break;
                case 202:
                        console.log("markAsReadNotification - "+jsonParsed.msg);
                        break;
                default:
                        console.log("markAsReadNotification - "+jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}

function getEmotionsDropdown(){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: { actiontype:'get_emotions_list'}
	})
	.done(function( msg ) {
	   //alert(msg);
       msg=escapeString(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        showFeelingsCategory(jsonParsed.msg);
                        break;
                case 202:
                        alert(jsonParsed.msg);
                        break;
                default:
                        alert(jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}


function showFeelingsCategory(emcatjson){
    var emDrpList='<div style="background-color:gray">';
    for(var eCat in emcatjson){
        emDrpList+='<div class="em"  onclick="return getEmotionlistData('+emcatjson[eCat].id+');">'+emcatjson[eCat].title+'</div>';
    }
    emDrpList+="</div>";
    if(document.getElementById("emotionslist")){
        document.getElementById("emotionslist").innerHTML=emDrpList;
    }
    
}

function getEmotionlistData(emcat){
    getEmotionsCatDropdown(emcat);
}
function getEmotionsCatDropdown(ecatid){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: { actiontype:'get_emotions_cat_dlist',emcatid:ecatid}
	})
	.done(function( msg ) {
	   //alert(msg);
       msg=escapeString(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        showFeelingsCategoryData(jsonParsed.msg);
                        break;
                case 202:
                        alert(jsonParsed.msg);
                        break;
                default:
                        alert(jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}
function showFeelingsCategoryData(emcatdjson){
    //alert(emcatdjson);
    var definition = {"smile":{"title":"Smile","codes":[":)",":=)",":-)"]},"sad-smile":{"title":"Sad Smile","codes":[":(",":=(",":-("]},"big-smile":{"title":"Big Smile","codes":[":D",":=D",":-D",":d",":=d",":-d"]},"cool":{"title":"Cool","codes":["8)","8=)","8-)","B)","B=)","B-)","(cool)"]},"wink":{"title":"Wink","codes":[":o",":=o",":-o",":O",":=O",":-O"]},"crying":{"title":"Crying","codes":[";(",";-(",";=("]},"sweating":{"title":"Sweating","codes":["(sweat)","(:|"]},"speechless":{"title":"Speechless","codes":[":|",":=|",":-|"]},"kiss":{"title":"Kiss","codes":[":*",":=*",":-*"]},"tongue-out":{"title":"Tongue Out","codes":[":P",":=P",":-P",":p",":=p",":-p"]},"blush":{"title":"Blush","codes":["(blush)",":$",":-$",":=$",":\">"]},"wondering":{"title":"Wondering","codes":[":^)"]}};
     var emotionsList=definition;
     //$.noConflict();
    //define(definition);
    var emotioncallmethod="";
    var emDrpList='<div style="background-color:gray">';
    var emoImgTags="";
    var etitle="";
    for(var eCat in emcatdjson){
        etitle=emcatdjson[eCat].title;
        etitle=replaceAll("DBL|QUOTE","",etitle)
        emoImgTags=escapeString1(etitle);
        emotioncallmethod='return setEmotionlistData1("'+emcatdjson[eCat].itemtype+'","'+emoImgTags+'");';
        //onclick=\''+emotioncallmethod+'\'
        emDrpList+='<div class="em" onclick=\''+emotioncallmethod+'\' >'+replaceAll("REP_","'",escapeString1(etitle))+'</div>';
    }
    emDrpList+="</div>";
    if(document.getElementById("emotionslist")){
        document.getElementById("emotionslist").innerHTML=emDrpList;
    }
    
}

function changeTextToemotions(str){
    //code of vikas
    return str;
}

function replaceAll(find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}

function setEmotionlistData1(itype,etitle){
    console.log(itype+etitle);
    var texttosave=itype+" "+replaceAll("REP_DBLQUOTE","'",etitle);
    if($("form#frmstupdt #st_emotionsfeeling")){
        
        //$("form#frmstupdt #st_emotionsfeeling_txt").css("display","none");
        $("form#frmstupdt #st_emotionsfeeling_div").css("display","");
        $("form#frmstupdt #st_emotionsfeeling_div").html("- "+replaceAll("REP_","'",texttosave));
    }
    $("form#frmstupdt #emotionslist").hide();
}
function selectEmotion(srcdata){
    console.log(srcdata);
}

var isStatusOpenedAsPopup=false;
function showStatusUpdateBox(){
    
    if($("#light_stupdtsec form#frmstupdt"))
    {
        $("#stupdthandler").toggle(100,
            function(){
                //alert($("#light_stupdtsec").css("display"));   
                if($("#light_stupdtsec").css("display")!="none"){
                    isStatusOpenedAsPopup=true;
                    $("#light_stupdtsec").addClass("statuspopupdiv"); 
                    lightbox_open("light","fade","stupdtsec");
                }
                else{
                    isStatusOpenedAsPopup=false;    
                            
                    lightbox_closeCurrent();
                } 
                $("#light_stupdtsec").css("display","");
            }
        )  
    }
}


function showMyLocationBox(){
    
    if($("#light_mylocation"))
    {
        $("#stupdthandler").toggle(100,
            function(){
                //alert($("#light_stupdtsec").css("display"));   
                if($("#light_mylocation").css("display")!="none"){
                    document.getElementById("post_location").style.display='none';
                    document.getElementById("locstr").value="";
                    isStatusOpenedAsPopup=false; 
                    lightbox_closeCurrent();
                }
                else{
                    isStatusOpenedAsPopup=true;
                    $("#light_mylocation").addClass("statuspopupdiv"); 
                    lightbox_open("light","fade","mylocation");
                    $("#light_mylocation").css("display","");
                } 
                
            }
        )  
    }
}

function createFrame(srcVal) {
    var ifrm = document.createElement("IFRAME");
    ifrm.setAttribute("id", "iframe_editpost");
    ifrm.setAttribute("src", srcVal);
    //ifrm.setAttribute("style", "display:none;");
    //width="500px" height="250px"
    ifrm.style.width = 500 + "px";
    ifrm.style.height = 250 + "px";
    $("#light_mylocationpost").html(ifrm);
    //document.body.appendChild(ifrm);
}

function showMyPostLocationBox(postid,postlocation){
    createFrame("mylocation.php?p=1&pid="+postid+"&ploc="+postlocation);
    if($("#light_mylocationpost"))
    {
        $("#stupdthandler").toggle(100,
            function(){
                //alert($("#light_stupdtsec").css("display"));   
                if($("#light_mylocationpost").css("display")!="none"){
                    //document.getElementById("post_location").style.display='none';
                    document.getElementById("locstr").value="";
                    isStatusOpenedAsPopup=false; 
                    lightbox_closeCurrent();
                }
                else{
                    isStatusOpenedAsPopup=true;
                    $("#light_mylocationpost").addClass("statuspopupdiv"); 
                    lightbox_open("light","fade","mylocationpost");
                    $("#light_mylocationpost").css("display","");
                }
            }
        )  
    }
}

$("#frmshareupdt #prvset").change(function(){
       var sharedWithval= $("#prvset").val();
       
       if(sharedWithval==sharewithtags.cluster){
            $("#frmshareupdt #st_myclusters").html($("#my_updated_cluster"));
            $("#frmshareupdt #st_myclusters").show();
       }
       else{
            $("#frmshareupdt #st_myclusters").hide();
       }
    });
    
function deleteMeCmnt(postid,cid,uid){
    if(!isNaN(uid)){
        performPostActions(postid,postactiontype.remove_comment,'','','','',cid,'','');
    }
}    

function getBirthdaYtemplate(casestr){
    switch(casestr){
        case "today":
            if(document.getElementById("birthday_wish_today")){
                return $("#birthday_wish_today").html(); 
            }
            break;
        case "tomorrow":
            if(document.getElementById("birthday_wish_tomorrow")){
                return $("#birthday_wish_tomorrow").html(); 
            }
            break;
        case "past":
            if(document.getElementById("birthday_wish_belated")){
                return $("#birthday_wish_belated").html(); 
            }
            break;
    }    
}

function updateBirthdayNotification(totalBdayCount,bdayAlertjsonLocal){
    var birthdate="0000-00-00";
    var birthmonth=0;
    var birthdate=0;
    var curmonth=0;
    var curdate=0;
    totalbdayupdated=0;
    var currentdate=new Date();
    curmonth=currentdate.getMonth();
    curdate=currentdate.getDate();
    
    var todaywish=getBirthdaYtemplate('today');
    var tomorrowwish=getBirthdaYtemplate('tomorrow');
    var pastwish=getBirthdaYtemplate('past');
    
    var diffleft=0;
    var b_alert="";
    var action_Date;
    var templateText="";
    var isupdated=false;
    
    
    
    //alert(bdayAlertjsonLocal.length);
    
    for(b_alert in bdayAlertjsonLocal){
        action_Date=bdayAlertjsonLocal[b_alert].days_left;
        //alert(action_Date);
        if(action_Date!='0000-00-00'){
            birthdate=new Date(action_Date);
            birthmonth=birthdate.getMonth();
            birthdate=birthdate.getDate();
            isupdated=false;
                
            if(curmonth==birthmonth){
                
                diffleft=curdate-birthdate;
                if(diffleft==0){
                    isupdated=true;
                    templateText=todaywish.format("dna.php?t="+bdayAlertjsonLocal[b_alert].ulink,bdayAlertjsonLocal[b_alert].uname,action_Date);
                    //alert(todaywish);
                    
                }
                else if(diffleft==1){
                    isupdated=true;
                    templateText=tomorrowwish.format("dna.php?t="+bdayAlertjsonLocal[b_alert].ulink,bdayAlertjsonLocal[b_alert].uname,action_Date);
                    //alert(tomorrowwish);
                }
                else if(diffleft<0){
                    isupdated=true;
                    templateText=pastwish.format("dna.php?t="+bdayAlertjsonLocal[b_alert].ulink,bdayAlertjsonLocal[b_alert].uname,action_Date);
                    //alert(pastwish);
                }
                if(isupdated){
                    totalbdayupdated++;
                    $("#notification_li #notificationsBody").append("<div class='notify'>"+templateText+"</div>");
                }
            }
        }
    }
    if(totalbdayupdated>0){
        $("#notification_li #notification_count").html(totalbdayupdated);
        $("#notification_li  #notification_count").css("display","");
    }
}

function getBirthdayNotifications(userid){
    //alert(userid+" - calling bday");
    totalbdayupdated=0;
    getNotifications(genericNotificationType.only_birthday,userid);
}


function showPostSettings(postid){
    ajaxGetPostSettings(postid);
}

function ajaxGetPostSettings(postid){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/getAjaxHtml.php",
	  	cache: false,
        async:false,
	  	data: { actiontype:'show_post_report_abused',report_abused_post_id:postid}
	})
	.done(function( msg ) {	
	       $("#load_htmls").html(msg);
	       var postsettingsid="light_edit_post_settings_"+postid;
            if($("#"+postsettingsid))
            {
                $("#stupdthandler").toggle(100,
                    function(){
                        //alert($("#light_stupdtsec").css("display"));   
                        if($("#"+postsettingsid).css("display")!="none"){
                            //document.getElementById("post_location").style.display='none';
                            //document.getElementById("locstr").value="";
                            isStatusOpenedAsPopup=false; 
                            lightbox_closeCurrent();
                        }
                        else{
                            isStatusOpenedAsPopup=true;
                            $("#"+postsettingsid).addClass("statuspopupdiv"); 
                            lightbox_open("light","fade","edit_post_settings_"+postid);
                            $("#"+postsettingsid).css("display","");
                        } 
                        
                    }
                )  
            }
		  
    })
    .fail(function(msg) {
	   console.log(msg);
	})
    .always(function() {
        
	});
    
}

function findAllCheckedReportType(report_post_classid,reporttypeid){
    var postid=0;
    var postidarr=report_post_classid.split("_");
    postid=postidarr[1];
    var replid="chk_"+postid+"_";
    var selectedreportedids="";
    var temp="";
    
    var selectedids=$( "input[class="+report_post_classid+"]:checked" );
    var selectedidLength=selectedids.length;
    var selectedClusters="";
    for(var i=0;i<selectedidLength;i++){
        //alert($(clusterselected[i]).attr("id"));
        temp=$(selectedids[i]).attr("id");
        selectedreportedids+= temp.replace(replid,"")+",";
    }
    selectedreportedids=selectedreportedids.substr(0,selectedreportedids.length-1);
    //alert(selectedreportedids);
    return selectedreportedids;
}

function savePostSettings(pid){
    var report_post_classid="rpt_"+pid;
    var selected_reported_ids=findAllCheckedReportType(report_post_classid,0);
    var isMarkedHidden=false;
    if(document.getElementById("hid_rpt_"+pid)){
        isMarkedHidden=document.getElementById("hid_rpt_"+pid).checked;// $("#hid_rpt_"+pid).is(":checked");
    }
    
    if(!isNaN(pid)){
        
        reportPostAbuse(pid,((isMarkedHidden==true || isMarkedHidden==1)?1:0),selected_reported_ids);
    }
    
}

function reportPostAbuse(postid,isMarkedHidden,selected_reported_ids){
    var actiondata={ actiontype:'post_reported_abuse',report_post_id:postid,report_as_hidden:isMarkedHidden,report_abuse_types:selected_reported_ids};
    
    console.log("report abuse: ");
    console.log(actiondata);
    
    $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: actiondata
	})
	.done(function( msg ) {
	   //alert(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        if(document.getElementById("feed"+postid)){
                           
                           if(parseInt(actiondata.report_as_hidden)==0){
                                $("#feed"+postid).remove();                           
                           }
                           if(selected_reported_ids.length>=1){
                            alertify.alert("Your request is sent to admin for approval");
                           } 
                        }                        
                        lightbox_closeCurrent();
                        //alert("followSources - "+jsonParsed.msg);
                        break;
                case 202:
                        alert("followSources - "+jsonParsed.msg);
                        break;
                default:
                        alert("followSources - "+jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}

function markAsReadAlerts(alerttype){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: { actiontype:'mark_as_read_mine_alerts',alerttype:alerttype}
	})
	.done(function( msg ) {
	   //alert(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        console.log("markAsReadAlerts - "+jsonParsed.msg);
                        break;
                case 202:
                        console.log("markAsReadAlerts - "+jsonParsed.msg);
                        break;
                default:
                        console.log("markAsReadAlerts - "+jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}

function changePostLocation(postid,postlocation){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: { actiontype:'edit_post_loc',idtoedit:postid,ploc:postlocation}
	})
	.done(function( msg ) {
	   //alert(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        window.location.reload();
                        //alert("followSources - "+jsonParsed.msg);
                        break;
                case 202:
                        alert("followSources - "+jsonParsed.msg);
                        break;
                default:
                        alert("followSources - "+jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}
function setPostLocation(postlocation,postid){
    //alert("postid: "+postid+" postlocation: "+postlocation);
    changePostLocation(postid,postlocation);
}


function getReplacedText(TextToReplace,jsonStr){
    if(isNaN(TextToReplace)){
        TextToReplace=TextToReplace.replace("{slink}",jsonStr.slink);
        TextToReplace=TextToReplace.replace("{Birthdate}",jsonStr.S_DOB);
        TextToReplace=TextToReplace.replace("{His/Her}",jsonStr.S_HisHer);
    }
   return TextToReplace; 
   //return (TextToReplace.replace("{slink}",jsonStr.slink).replace("{Birthdate}",jsonStr.S_DOB).replace("{His/Her}",jsonStr.S_HisHer));
   
}
function redirectTo(redirectUrl){
    window.location.href=redirectUrl.replace("{visitorid}",requserid);
}
function markActRead(Actid){
    alert("markActRead::activity id: "+Actid);
    
   $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: { actiontype:'mark_as_read_activity_for_me',actid:Actid}
	})
	.done(function( msg ) {
	   //alert(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        $(".notify-"+Actid).remove();
                        console.log("markAsReadNotification - "+jsonParsed.msg);
                        break;
                case 202:
                        console.log("markAsReadNotification - "+jsonParsed.msg);
                        break;
                default:
                        console.log("markAsReadNotification - "+jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});

}

function getNotifiedActivities(uid){
    getNewNotfiedActivities(nMaxNotifiedActID,uid);
}

function getNewNotfiedActivities(nMaxNotifiedActIDLocal,uid){
    $.ajax({
	  	type: "POST",
	  	url: "ajax/generic_crudoperations.php",
	  	cache: false,
	  	data: { actiontype:'get_mynotificationspopup',requested_by_uid:uid,nMaxNotifyIDRead:nMaxNotifiedActIDLocal}
	})
	.done(function( msg ) {
	   //alert(msg);
	   var jsonParsed=$.parseJSON(msg);
       if(!isNaN(jsonParsed.err)){ //means have some code
            switch(parseInt(jsonParsed.err)){
                case 200:
                        var nMinMax= getMinMax(jsonParsed.msg, "aid");
                        if(nLeastNotfiedActID!=0 && nLeastNotfiedActID>nMinMax.min)
                            nLeastNotfiedActID=nMinMax.min;
                        else if(nLeastNotfiedActID==0)
                            nLeastNotfiedActID=nMinMax.min;
                            
                        if(nMaxNotifiedActID<nMinMax.max)
                            nMaxNotifiedActID=nMinMax.max;
                        
                        if(nMaxNotifiedActID>nMaxNotifiedActIDLocal){    
                            notJson=jsonParsed;
                            console.log("Notfied Entries: Min: "+nLeastNotfiedActID+" Max: "+nMaxNotifiedActID);
                            //alert("getNotifiedActivities - "+jsonParsed.msg);
                        }
                        
                        break;
                default:
                        //alert("getNotifiedActivities - "+jsonParsed.msg);
                        break;
            }
        }
    })
    .fail(function(msg) {
	   
	})
    .always(function() {
        
	});
}


function getMinMax(jsonMsg, type) {
  var out = Array();
  for(var i=0;i<jsonMsg.length;i++){
    out[i]=parseInt(jsonMsg[i]["aid"]);
  } 
  return { min: Math.min.apply(null,out), max: Math.max.apply(null,out) };
}